package com.baibei.pay.recharge;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.baibei.basic.WebViewFragment;
import com.baibei.model.InoutFundParam;
import com.baibei.pay.withdraw.WithdrawSuccessFragment;
import com.baibei.sdk.TokenEvent;
import com.baibei.widget.RaeWebView;
import com.baibei.widget.RaeWebViewClient;
import com.blankj.utilcode.utils.LogUtils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;

import org.greenrobot.eventbus.EventBus;

/**
 * h5支付桥接
 * Created by shenminjie on 2017/8/18.
 * mail:shenminjie@100bei.com
 */

public class PaymentWebViewFragment extends WebViewFragment {

    /**
     * 入参
     */
    private InoutFundParam mParam;
    public static final String JAVASCRIPT_NAME = "payment";

    /**
     * 根据form数据界面
     *
     * @param param param
     * @return WebViewFragment
     */
    public static PaymentWebViewFragment newInstance(InoutFundParam param) {
        Bundle args = new Bundle();
        args.putParcelable("param", param);
        args.putString("url", param.getUrl());
        PaymentWebViewFragment fragment = new PaymentWebViewFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam = getArguments().getParcelable("param");
        }
    }

    @SuppressLint("AddJavascriptInterface")
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mWebView.addJavascriptInterface(new RechargeInterface(), JAVASCRIPT_NAME);
        super.onViewCreated(view, savedInstanceState);
    }

    /**
     * 回调callback
     * javascript调用
     */
    private class RechargeInterface {

        @JavascriptInterface
        public String getUserInfo() {
            LogUtils.e("js参数", mParam);
            return new Gson().toJson(mParam);
        }

        @JavascriptInterface
        public void show(final String info) {
            showSth(info);
        }

        @JavascriptInterface
        public void show(final String info1, final String info2) {
            showSth(info1 + ";" + info2);
        }

        @JavascriptInterface
        public void show(final String info1, final String info2, final String info3) {
            showSth(info1 + ";" + info2 + ";" + info3);
        }

        @JavascriptInterface
        public void finish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getActivity().finish();
                }
            });
        }

        @JavascriptInterface
        public void loginAction(){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //清空数据，登录
                    SessionManager.getDefault().clear();
                    EventBus.getDefault().post(new TokenEvent());
                }
            });
        }

        @JavascriptInterface
        public void withDrawSuccess() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    WithdrawSuccessFragment fragment = new WithdrawSuccessFragment();
                    fragment.setOnListener(new WithdrawSuccessFragment.OnSuccessListener() {
                        @Override
                        public void onSuccessListener(DialogFragment fragment) {
                            //成功返回
                            fragment.dismiss();
                            finish();
                        }
                    });
                    fragment.show(getFragmentManager(), "success");
                }
            });
        }

        private void showSth(final String text) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new DialogBuilder(getContext()).setMessage(text).show();
                }
            });
        }

        private void runOnUiThread(Runnable action) {
            if (getActivity() != null) {
                getActivity().runOnUiThread(action);
            }
        }
    }

    public WebViewClient getWebViewClient() {
        return new RaeWebViewClient(mProgressBar, mPlaceHolderLayout) {
            @Override
            protected void showEmpty() {
//                super.showEmpty();
//                if (getActivity() != null) {
//                    getActivity().setTitle("网络连接失败");
//                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (mParam.getPayModeInfo() != null
                        && !TextUtils.isEmpty(mParam.getPayModeInfo().getFundCallbackUrl())
                        && url.startsWith(mParam.getPayModeInfo().getFundCallbackUrl())) {
                    if (getActivity() != null) {
                        getActivity().finish();
                    }
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                dismissProgress();
            }
        };
    }

    @Override
    public WebView getWebView() {
        //禁止问题
        return new RaeWebView(getContext().getApplicationContext()) {
            @Override
            public boolean onKeyDown(int keyCode, KeyEvent event) {
                return false;
            }
        };
    }
}
